package com.example.Config;

import com.example.Service.UserService;
import com.example.pojo.User;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.security.Security;

//自定义的Realm  需要继承AuthorizingRealm父类
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");

        //授权SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        /*info.addStringPermission("user:addUser");*/

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        //设置当前用户的权限
        info.addStringPermission(user.getPermission());


        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");

        /*//用户名密码   数据库取得
        String username = "cp";
        //密码随意改，用户名现在只能记得上次更改时的
        String password = "1234";
        //连接真实的数据库*/


        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;



        /*System.out.println(userToken.getUsername());
        System.out.println(username);
        System.out.println(password);
        if(!userToken.getUsername().equals(username)){
            return null; //抛出用户名异常
        }*/

        User user = userService.queryUserByUsername(userToken.getUsername());

        if(user==null){//用户名不正确
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);

        //shior 为了保密，会自动做密码验证，此处无需在做密码验证
        //shiro也可以对密码加密 md5 加密  和 md5 盐池加密
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
